<script setup>
import { useRoute } from "vue-router";
import {computed, onMounted, reactive, ref, watch} from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import {router} from "@/router/index.js";
import {Message} from "@element-plus/icons-vue";

const route = useRoute();
const productId = route.params.id;

const car = ref(null);
const carConfig = ref({
  color: "默认颜色",
  wheel: "默认车轮",
  seat: "默认座椅",
  colorPrice: 0,
  wheelPrice: 0,
  seatPrice: 0
});
const totalPrice = ref(0);
const $urlImage = "http://smh25828x.hn-bkt.clouddn.com/imgs/"; // 默认的图片路径

const getCarById = async () => {
  try {
    const response = await axios.get(`/car/getCarById`, { params: { id: productId } });
    car.value = response.data;
    totalPrice.value = car.value.price;  // 默认总价是基础价格
  } catch (error) {
    ElMessage.error(error.message);
  }
};

const geyPrice = (price) => {
  return ((price) / 100).toFixed(0);
};

const toggleConfig = ref(false); // 用于控制配置面板的显示与隐藏

const updateTotalPrice = () => {
  totalPrice.value = car.value.price + carConfig.value.colorPrice + carConfig.value.wheelPrice + carConfig.value.seatPrice;
};

const handleColorChange = (color, price) => {
  carConfig.value.color = color;
  carConfig.value.colorPrice = price;
  updateTotalPrice();
};

const handleWheelChange = (wheel, price) => {
  carConfig.value.wheel = wheel;
  carConfig.value.wheelPrice = price;
  updateTotalPrice();
};

const handleSeatChange = (seat, price) => {
  carConfig.value.seat = seat;
  carConfig.value.seatPrice = price;
  updateTotalPrice();
};

const next = async () => {
  if (!isVerified.value) {
    ElMessage.error("请先验证验证码！");
    return;
  }
  // 先验证表单
  refLoginForm.value.validate(async (valid) => {
    if (valid) {
      // 表单验证通过后，跳转到下一个页面
      await router.push({
        name: "configureNext", // 你可以替换成你希望跳转的路由名称
        query: {
          id: productId,
          color: carConfig.value.color,
          wheel: carConfig.value.wheel,
          seat: carConfig.value.seat,
          colorPrice: carConfig.value.colorPrice,
          wheelPrice: carConfig.value.wheelPrice,
          seatPrice: carConfig.value.seatPrice,
          totalPrice: totalPrice.value,
          carImageUrl: getCarImageUrl.value,  // 传递图片URL
          province: form.value.province,
          city: form.value.city,
          district: form.value.district,
          detailAddress: form.value.detailAddress,
          fullAddress: [
            form.value.provinceName || '',
            form.value.cityName || '',
            form.value.districtName || '',
            form.value.detailAddress || ''
          ].filter(item => item).join(' '), // 去除空值并拼接成完整地址
          name: form.value.name,  // 姓名
          telephone: form.value.telephone  // 手机号
        }
      });
    } else {
      console.log('验证失败', invalidFields);
      ElMessage.error("请填写完整的表单！");
    }
  });
};



// 获取不同颜色的图片链接
const getCarImageUrl = computed(() => {
  if (!car.value) return '';

  // 根据配置颜色选择车图片
  switch (carConfig.value.color) {
    case '红色':
      return 'http://smh25828x.hn-bkt.clouddn.com/imgs/car3.jpg';  // 红色车图片
    case '蓝色':
      return 'http://smh25828x.hn-bkt.clouddn.com/imgs/car1.jpg'; // 蓝色车图片
    case '绿色':
      return 'http://smh25828x.hn-bkt.clouddn.com/imgs/car6.jpg';  // 绿色车图片
    case '黄色':
      return 'http://smh25828x.hn-bkt.clouddn.com/imgs/car2.jpg';  // 黄色车图片
    case '黑色':
      return 'http://smh25828x.hn-bkt.clouddn.com/imgs/car10.jpg';  // 黑色车图片
    case '紫色':
      return 'http://smh25828x.hn-bkt.clouddn.com/imgs/car0.jpg';  // 紫色车图片
    default:
      return $urlImage + car.value.imgs;  // 默认车图片，拼接 URL
  }
});

const toggleAddressPanel = ref(false); // 用于控制地址选择面板的显示与隐藏
const form = ref({
  province: "",
  provinceName: "",
  city: "",
  cityName: "",
  district: "",
  districtName: "",
  detailAddress: "",
  name: "",
  telephone: "18849045379",
  code: ""
})

const provinces = ref([]);
const cities = ref([]);
const districts = ref([]);

const initProvinceData = () => {
  axios.get('/china/getAllProvince').then(response => {
    provinces.value = response.data;
  });
};

// 根据省份获取城市列表，并设置为市级 el-select 的 options
const handleProvinceChange = () => {
  axios.get('/address/getAllCities', {
    params: {"provinceId": form.value.province}
  }).then((response) => {
    cities.value = response.data;
    // 设置 provinceName
    const selectedProvince = provinces.value.find(p => p.id === form.value.province);
    if (selectedProvince) {
      form.value.provinceName = selectedProvince.name;
    }
  }).catch((error) => {
    console.log(error);
  });
  // 清空之前的数据
  districts.value = [];
  form.value.city = '';
  form.value.district = '';
  form.value.cityName = '';
  form.value.districtName = '';
};

// 根据城市获取区县列表，并设置为区级 el-select 的 options
const handleCityChange = () => {
  axios.get('/address/getAllDistricts', {
    params: {"cityId": form.value.city}
  }).then((response) => {
    districts.value = response.data;
    // 设置 cityName
    const selectedCity = cities.value.find(c => c.id === form.value.city);
    if (selectedCity) {
      form.value.cityName = selectedCity.name;
    }
  }).catch((error) => {
    console.log(error);
  });
  form.value.district = '';
  form.value.districtName = '';
};

// 根据区县设置 districtName
const handleDistrictChange = () => {
  const selectedDistrict = districts.value.find(d => d.id === form.value.district);
  if (selectedDistrict) {
    form.value.districtName = selectedDistrict.name;
  }
};

const refLoginForm = ref(null);
const rules = reactive({
  name: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  telephone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机格式不正确', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {min: 4, max: 4, message: '长度必须是4位', trigger: 'blur'}
  ]
});
const smsDisabled = ref(false);
const smsText = ref('发送短信验证码');
const sendSms = () => {
      smsDisabled.value = true;
      //发送短信
      axios.get(`/users/sendSms/${form.value.telephone}`).then(resp => {
        //发送成功
        ElMessage({
          message: resp.data,
          type: 'success'
        });
      }).catch(error => {
        //发送失败
        ElMessage.error(error.response.data);
      }).finally(() => {
        //按钮文字变成倒计时
        let seconds = 15;
        smsText.value = `${seconds}秒后重新发送`;
        let timer = setInterval(() => {
          seconds--;
          if (seconds > 0) {
            smsText.value = `${seconds}秒后重新发送`;
          } else {
            //修改文字
            smsText.value = "发送短信验证码";
            //按钮可用
            smsDisabled.value = false;
            //清除定时器
            clearInterval(timer);
          }
        }, 1000);
      });
}
const isVerified = ref(false);  // 用于存储验证码验证的状态
const loadingVerification = ref(false); // 验证按钮加载状态

const verifyCode = async () => {
  if (!form.value.code) {
    ElMessage.error('请输入验证码');
    return;
  }

  loadingVerification.value = true;
  try {
    const response = await axios.post('/productsOrders/verifyCode', {
      telephone: form.value.telephone,
      code: form.value.code
    });
    if (response.data === "success") {
      ElMessage.success('验证码验证成功');
      isVerified.value = true;  // 设置验证码验证成功
    } else {
      ElMessage.error('验证码验证错误');
    }
  } catch (error) {
    ElMessage.error('验证码验证失败，请稍后再试');
  } finally {
    loadingVerification.value = false;
  }
};



// 监听carConfig.color的变化，确保更新图片链接
watch(() => carConfig.value.color, () => {
  getCarImageUrl.value; // 强制更新图片链接
}, { immediate: true });

onMounted(() => {
  getCarById();
  initProvinceData();
});
</script>

<template>
  <h2 class="title">车辆价格配置:</h2>
  <div class="Configure">
    <div v-if="car" class="left-panel">
      <div class="card">
        <el-form ref="refLoginForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入您的姓名"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="telephone">
            <el-input v-model="form.telephone" placeholder="请输入您的手机号"></el-input>
          </el-form-item>
          <el-form-item label="验证码：" prop="code">
            <div class="form-item-container">
              <el-input v-model="form.code" maxlength="4" minlength="4" placeholder="验证码" style="width: 90px; margin-right: 10px;"></el-input>
              <el-button type="text" :disabled="smsDisabled" @click="sendSms">
                <el-icon :size="20"><Message /></el-icon>
                {{ smsText }}
              </el-button>
            </div>
          </el-form-item>
          <!-- 添加验证按钮 -->
          <el-form-item>
            <el-button type="primary" @click="verifyCode" :disabled="loadingVerification || isVerified">验证验证码</el-button>
          </el-form-item>
        </el-form>

        <table>
          <p class="divider"></p>
          <tr>
            <td>建议零售价：</td>
            <td>¥{{ car.price }}</td>
          </tr>
          <tr>
            <td>综合耗油量（EU）：</td>
            <td>{{ car.fuelConsumption }} 升/100公里</td>
          </tr>
          <tr>
            <td>最高车速：</td>
            <td>{{ car.maxSpeed }} 公里/小时</td>
          </tr>
          <tr>
            <td>百公里加速：</td>
            <td>{{ car.acceleration }} 秒</td>
          </tr>
          <p class="divider"></p>
          <tr>
            <td>预估总价：</td>
            <td>¥{{ totalPrice }}</td>
          </tr>
          <tr>
            <td>购车意向金：</td>
            <td style="color: red;">¥{{ geyPrice(totalPrice) }}</td>
            <td>
              <button @click="toggleConfig = !toggleConfig">+</button>
            </td>
          </tr>
          <p class="divider"></p>
          <tr>
            <td>您的现居住地：</td>
            <td>
              <span v-if="form.provinceName">{{ form.provinceName }} {{ form.cityName }} {{ form.districtName }} {{ form.detailAddress }}</span>
              <span v-else>请选择或填写地址</span>
            </td>
            <td>
              <button @click="toggleAddressPanel = !toggleAddressPanel">+</button>
            </td>
          </tr>
        </table>


        <div v-if="toggleConfig" class="config-panel">
          <h3>选择车辆配置</h3>

          <div class="config-item">
            <label>车身颜色：</label>
            <div class="options">
              <button
                  class="option"
                  :class="{'selected': carConfig.color === '默认颜色'}"
                  @click="handleColorChange('默认颜色', 0)">
                默认颜色
                <span v-if="carConfig.color === '默认颜色'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.color === '红色'}"
                  @click="handleColorChange('红色', 2000)"
                  style="background-color: red; color: white;">
                红色 (+¥2000)
                <span v-if="carConfig.color === '红色'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.color === '蓝色'}"
                  @click="handleColorChange('蓝色', 3000)"
                  style="background-color: blue; color: white;">
                蓝色 (+¥3000)
                <span v-if="carConfig.color === '蓝色'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.color === '绿色'}"
                  @click="handleColorChange('绿色', 2500)"
                  style="background-color: green; color: white;">
                绿色 (+¥2500)
                <span v-if="carConfig.color === '绿色'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.color === '黄色'}"
                  @click="handleColorChange('黄色', 1500)"
                  style="background-color: #cfb269; color: white;">
                黄色 (+¥1500)
                <span v-if="carConfig.color === '黄色'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.color === '黑色'}"
                  @click="handleColorChange('黑色', 4000)"
                  style="background-color: black; color: white;">
                黑色 (+¥4000)
                <span v-if="carConfig.color === '黑色'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.color === '紫色'}"
                  @click="handleColorChange('紫色', 3500)"
                  style="background-color: purple; color: black;">
                紫色 (+¥3500)
                <span v-if="carConfig.color === '紫色'" class="checkmark">✔</span>
              </button>
            </div>
          </div>

          <div class="config-item">
            <label>车轮选择：</label>
            <div class="options">
              <button
                  class="option"
                  :class="{'selected': carConfig.wheel === '默认车轮'}"
                  @click="handleWheelChange('默认车轮', 0)">
                默认车轮
                <span v-if="carConfig.wheel === '默认车轮'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.wheel === '1号车轮'}"
                  @click="handleWheelChange('1号车轮', 1500)">
                1号车轮 (+¥1500)
                <span v-if="carConfig.wheel === '1号车轮'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.wheel === '2号车轮'}"
                  @click="handleWheelChange('2号车轮', 2000)">
                2号车轮 (+¥2000)
                <span v-if="carConfig.wheel === '2号车轮'" class="checkmark">✔</span>
              </button>
            </div>
          </div>

          <div class="config-item">
            <label>座椅选择：</label>
            <div class="options">
              <button
                  class="option"
                  :class="{'selected': carConfig.seat === '默认座椅'}"
                  @click="handleSeatChange('默认座椅', 0)">
                默认座椅
                <span v-if="carConfig.seat === '默认座椅'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.seat === '1号座椅'}"
                  @click="handleSeatChange('1号座椅', 1000)">
                1号座椅 (+¥1000)
                <span v-if="carConfig.seat === '1号座椅'" class="checkmark">✔</span>
              </button>
              <button
                  class="option"
                  :class="{'selected': carConfig.seat === '2号座椅'}"
                  @click="handleSeatChange('2号座椅', 1500)">
                2号座椅 (+¥1500)
                <span v-if="carConfig.seat === '2号座椅'" class="checkmark">✔</span>
              </button>
            </div>
          </div>

        </div>

        <div v-if="toggleAddressPanel">
          <el-row>
            <el-col :span="7">
              <el-form-item label="省" prop="province">
                <el-select v-model="form.province" @change="handleProvinceChange" style="width: 200px">
                  <el-option v-for="province in provinces" :key="province.id" :label="province.name" :value="province.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="市" prop="city">
                <el-select v-model="form.city" @change="handleCityChange" style="width: 200px">
                  <el-option v-for="city in cities" :key="city.id" :label="city.name" :value="city.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="县" prop="district">
                <el-select v-model="form.district" @change="handleDistrictChange" style="width: 200px">
                  <el-option v-for="district in districts" :key="district.id" :label="district.name" :value="district.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="详细地址" prop="detailAddress">
            <el-input v-model="form.detailAddress" placeholder="请输入详细地址" style="width: 300px"></el-input>
          </el-form-item>
        </div>

        <el-form-item>
          <el-button type="primary" @click="next" :disabled="!isVerified">下一步
            <el-popover
                placement="top-start"
                :width="280"
                trigger="hover"
                content="验证码验证成功后才能点击下一步">
              <template #reference>
                    <span style="cursor: pointer;">
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="12" height="12">
                        <path d="M12 0a12 12 0 1 0 12 12A12.013 12.013 0 0 0 12 0zm0 22a10 10 0 1 1 10-10 10.012 10.012 0 0 1-10 10zm1-15h-2v2h2zm0 4h-2v6h2z"/>
                      </svg>
                    </span>
              </template>
            </el-popover></el-button>
        </el-form-item>
      </div>
    </div>

    <!-- 动态改变图片 -->
    <div v-if="car" class="right-panel">
      <img :src="getCarImageUrl" alt="车辆图片" />
    </div>


  </div>
</template>

<style scoped>
/* 样式代码保持不变 */
.right-panel img {
  max-width: 100%;
  max-height: 80%;
  object-fit: contain;
}
.title {
  font-size: 1.5rem;
  margin: 20px 10%;
}

.Configure {
  display: flex;
  justify-content: space-between;
  margin: 20px 10%;
  background: #EAEAEF;
  padding: 20px;
  border-radius: 8px;
}

.left-panel {
  width: 40%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.right-panel {
  width: 60%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.Configure .divider {
  border-top: 2px solid black;
  width: 100%;
  margin: 20px 0;
}

.Configure button {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
}

.Configure button:hover {
  background-color: #66b1ff;
}

.right-panel img {
  max-width: 100%;
  max-height: 80%;
  object-fit: contain;
}

table {
  width: 100%;
  border-collapse: collapse;
}

table td {
  padding: 8px;
  border-bottom: 1px solid #ddd;
}

table td:first-child {
  font-weight: bold;
}

.config-panel {
  margin-top: 20px;
}

.config-item {
  margin-bottom: 20px;
}

.options {
  display: flex;
  gap: 8px;
  flex-wrap: wrap; /* 添加这个属性，使按钮可以换行 */
}

.option {
  padding: 5px 12px;
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
  font-size: 0.9rem;
  white-space: nowrap;  /* 防止文字换行 */
  flex: 0 1 auto; /* 使每个按钮的宽度自适应，但在必要时会换行 */
}


.option.selected {
  background-color: #a4e3c5;
  color: white;
}

.option:hover {
  background-color: #409eff;
  color: white;
}

.checkmark {
  margin-left: 5px;
  font-size: 1rem;
}

button:focus {
  outline: none;
}
</style>
